import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPriorityScheduleDemo {

	 
	private static final int MAX_PARKING = 5;
	static ThreadPriorityScheduleDemo instance = new ThreadPriorityScheduleDemo();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		
		ExecutorService service = Executors.newCachedThreadPool();
		
		for(int i=0;i<20;i++){
			service.execute(new Runnable(){

				@Override
				public void run() {
					Random i = new Random();
					int j = i.nextInt(10);
					instance.busEnter(new Bus("粤A12345", 2,j ));
				}
			});	
		}

		

		while(true){
			instance.busQuit();
		}
	}
	
	private static final PriorityBlockingQueue<Bus> busStation = new PriorityBlockingQueue<Bus>(MAX_PARKING);
	
	/**
	 * 车辆进站
	 * @param bus
	 */
	private void busEnter(Bus bus){
		System.out.println("进站-->"+bus.toString());
		if(busStation.size()<MAX_PARKING)
			busStation.add(bus);
		else
			System.out.println("站内车位已满");
		
	}
	
	/**
	 * 车辆出站
	 */
    private void busQuit(){
    	try {
			Bus bus = busStation.take();
			System.out.println("出站-->"+bus.toString());
		} catch (InterruptedException e) {
			
		}
	}
	
    /**
     * 车实例
     * @author jiangw
     *
     * 2010-3-26
     */
	static class Bus implements Comparable<Bus>{
		
		private String busNo;
		private Integer busType;
		private Integer level;
		private Bus() {}

		private Bus(String busNo, Integer busType, Integer level) {
			super();
			this.busNo = busNo;
			this.busType = busType;
			this.level = level;
		}

		public String getBusNo() {
			return busNo;
		}

		public void setBusNo(String busNo) {
			this.busNo = busNo;
		}

		public Integer getBusType() {
			return busType;
		}

		public void setBusType(Integer busType) {
			this.busType = busType;
		}
		

		public Integer getLevel() {
			return level;
		}

		public void setLevel(Integer level) {
			this.level = level;
		}

		@Override
		public int compareTo(Bus o) {
//			System.out.println(busStation.toString());
			if(o instanceof Bus){
//				System.out.println(level+":"+o.level);
//				System.out.println((level>o.level)?1:-1);
				return (level>o.level)?1:-1;
			}
			return 0;
		}

		@Override
		public String toString() {
			return "当前车信息：种类["+busType+"]车牌["+busNo+"]优先级["+level+"]";
		}
	}

}
